/**
 * Copyright (c) 2011-2016, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jfinal.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Invocation;
import com.jfinal.mvc.render.ActionException;
import com.jfinal.mvc.render.Render;
import com.jfinal.mvc.render.RenderException;
import com.jfinal.mvc.render.RenderFactory;

import java.util.ArrayList;

/**
 * ActionHandler
 */
final class ActionHandler {
	private static final Logger logger = LoggerFactory.getLogger(ActionHandler.class);

	private static final RenderFactory renderFactory = RenderFactory.me();
	private final ActionMapping actionMapping;

	ActionHandler(ActionMapping actionMapping) {
		this.actionMapping = actionMapping;
	}

	/**
	 * handle
	 * 1: Action action = actionMapping.getAction(target)
	 * 2: new Invocation(...).invoke()
	 * 3: render(...)
	 */
	final void handle(String target, HttpServletRequest request, HttpServletResponse response) {
		if (target.indexOf('.') != -1) {
			return;
		}

		ArrayList<Object> urlPara = new ArrayList<>();
		Action action = actionMapping.getAction(target, urlPara);

		if (action == null) {
			if (logger.isWarnEnabled()) {
				String qs = request.getQueryString();
				logger.warn("404 Action Not Found: " + (qs == null ? target : target + "?" + qs));
			}
			renderFactory.getErrorRender(404).setContext(request, response).render();
			return;
		}

		try {
			Controller controller = action.getControllerClass().newInstance();
			controller.init(request, response);

			new Invocation(action, controller, urlPara.toArray()).invoke();

			Render render = controller.getRender();
			if (render instanceof ActionRender) {
				String actionUrl = ((ActionRender) render).getActionUrl();
				if (target.equals(actionUrl))
					throw new RuntimeException("The forward action url is the same as before.");
				else
					handle(actionUrl, request, response);
				return;
			}

			if (render == null)
				render = renderFactory.getDefaultRender(action.getViewPath() + action.getMethodName());
			render.setContext(request, response, action.getViewPath()).render();
		} catch (RenderException e) {
			if (logger.isErrorEnabled()) {
				String qs = request.getQueryString();
				logger.error(qs == null ? target : target + "?" + qs, e);
			}
		} catch (ActionException e) {
			int errorCode = e.getErrorCode();
			if (errorCode == 404 && logger.isWarnEnabled()) {
				String qs = request.getQueryString();
				logger.warn("404 Not Found: " + (qs == null ? target : target + "?" + qs));
			} else if (errorCode == 401 && logger.isWarnEnabled()) {
				String qs = request.getQueryString();
				logger.warn("401 Unauthorized: " + (qs == null ? target : target + "?" + qs));
			} else if (errorCode == 403 && logger.isWarnEnabled()) {
				String qs = request.getQueryString();
				logger.warn("403 Forbidden: " + (qs == null ? target : target + "?" + qs));
			} else if (logger.isErrorEnabled()) {
				String qs = request.getQueryString();
				logger.error(qs == null ? target : target + "?" + qs, e);
			}
			e.getErrorRender().setContext(request, response, action.getViewPath()).render();
		} catch (Throwable t) {
			if (logger.isErrorEnabled()) {
				String qs = request.getQueryString();
				logger.error(qs == null ? target : target + "?" + qs, t);
			}
			renderFactory.getErrorRender(500).setContext(request, response, action.getViewPath()).render();
		}
	}
}
